import UploadModal from '@/pages/admin/fileInfo/components/UploadModal';
import {
  deleteFileInfoUsingPost,
  listFileInfoVoByPageUsingPost,
} from '@/services/backend/fileInfoController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */

  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const actionRef = useRef<ActionType>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.FileInfoVO) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteFileInfoUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  const isImageUrl = (url: string): boolean => {
    // 简单的正则表达式来判断是否为图片URL
    return /\.(jpg|jpeg|png|gif|svg)$/i.test(url);
  };

  const columns: ProColumns<API.FileInfoVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '名称',
      dataIndex: 'name',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '大小',
      dataIndex: 'size',
      valueType: 'text',
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'text',
    },
    {
      title: '文件地址',
      dataIndex: 'url',
      valueType: 'image',
      render: (dom, row) => {
        if (row.url) {
          if (!isImageUrl(row.url)) {
            return <>{row.url}</>;
          } else {
            return dom;
          }
        }
      },
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '创建人名称',
      dataIndex: ['user', 'username'],
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="upload"
            href={record.url}
            // onClick={() => {
            //   setUpdateModalVisible(true);
            //   setCurrentRow(record);
            // }}
          >
            下载
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.FileInfoVO>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        options={false}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setUpdateModalVisible(true);
            }}
          >
            <PlusOutlined /> 上传
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listFileInfoVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.FileInfoQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*上传悬浮窗*/}
      <UploadModal
        modalVisible={updateModalVisible}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
        onSubmit={(val) => {
          console.log(val);
          setUpdateModalVisible(false);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};
export default TableList;
